﻿using ICodeShare.UI.Controls.Demo.ViewModels;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ICodeShare.UI.Controls.Demo.ExampleViews
{
    /// <summary>
    /// DatePickerView.xaml 的交互逻辑
    /// </summary>
    public partial class DatePickerView : UserControl
    {
        public DatePickerView()
        {
            InitializeComponent();
            this.Loaded += DatePickerView_Loaded;
        }

        void DatePickerView_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= DatePickerView_Loaded;
            this.DataContext = new DatePickerViewModel();
            FutureDatePicker.BlackoutDates.AddDatesInPast();
            LoadLocales();
            LocaleCombo.SelectionChanged += LocaleCombo_SelectionChanged;
            LocaleCombo.SelectedItem = "zh-CN";
        }

        private void LoadLocales()
        {
            foreach (var ci in CultureInfo.GetCultures(CultureTypes.AllCultures)
                .Where(ci => ci.Calendar is GregorianCalendar)
                .OrderBy(ci => ci.Name))
            {
                LocaleCombo.Items.Add(ci.Name);
            }
        }

        private void LocaleCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var lang = System.Windows.Markup.XmlLanguage.GetLanguage((string)LocaleCombo.SelectedItem);
            LocaleDatePicker.Language = lang;
            LocaleDatePickerRTL.Language = lang;

            //HACK: The calendar only refresh when we change the date
            LocaleDatePicker.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(1);
            LocaleDatePicker.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(-1);
            LocaleDatePickerRTL.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(1);
            LocaleDatePickerRTL.DisplayDate = LocaleDatePicker.DisplayDate.AddDays(-1);
        }

        public void CalendarDialogOpenedEventHandler(object sender, DialogOpenedEventArgs eventArgs)
        {
            calSelected.SelectedDate = ((DatePickerViewModel)DataContext).Date;
        }

        public void CalendarDialogClosingEventHandler(object sender, DialogClosingEventArgs eventArgs)
        {
            if (!Equals(eventArgs.Parameter, "1")) return;

            if (!calSelected.SelectedDate.HasValue)
            {
                eventArgs.Cancel();
                return;
            }

            ((DatePickerViewModel)DataContext).Date = calSelected.SelectedDate.Value;
        }
    }
}
